/**
 * This file is Copyright © 2008 Software Craftsmen Limited. All Rights Reserved.
 */
package com.softwarecraftsmen.orogeny.filing.absolutePathMetaData.posixPermissions;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.Locale;

public class PosixNonClassPermissions
{
	@NotNull
	public static final PosixNonClassPermissions NoSpecialPermissions = new PosixNonClassPermissions(false, false, false);

	private final boolean stickyBit;
	private final boolean setGroupIdentifierUponExecution;
	private final boolean setUserIdentifierUponExecution;

	public PosixNonClassPermissions(final boolean stickyBit, final boolean setGroupIdentifierUponExecution, final boolean setUserIdentifierUponExecution)
	{
		this.stickyBit = stickyBit;
		this.setGroupIdentifierUponExecution = setGroupIdentifierUponExecution;
		this.setUserIdentifierUponExecution = setUserIdentifierUponExecution;
	}

	/*
		On files, this causes the text segment of the program to remain in swap space on some OS (HP-UX, MacOSX and NetBSD; it has been dropped from newer versions of OpenBSD, FreeBSD and Solaris and is unused in Linux)
		On directories, it allows only the directory owner or a file owner to delete, rename or move)
	 */
	public boolean stickyBit()
	{
		return stickyBit;
	}

	/*
		On files, when executed, they are run with the permissions of the group they belong to and not those of the current user
		On directories. new files and subdirectories inherit the parent's group rather than that of the current user
	 */
	public boolean setGroupIdentifierUponExecution()
	{
		return setGroupIdentifierUponExecution;
	}

	/*
		On files, when executed, they are run with the permissions of the owner and group and not those of the current user
		On directories. new files and subdirectories inherit the parent's owner rather than belong to the current user
		It is ignored on most UNIX systems and Linux; behaviour varies on FreeBSD
	 */
	public boolean setUserIdentifierUponExecution()
	{
		return setUserIdentifierUponExecution;
	}

	@NotNull
	public String toString()
	{
		return String.format(Locale.UK, "stickyBit:%1$s, setGroupIdentifierUponExecution:%2$s, setUserIdentifierUponExecution:%3$s", stickyBit, setGroupIdentifierUponExecution, setUserIdentifierUponExecution);
	}

	public boolean equals(final @Nullable Object o)
	{
		if (this == o)
		{
			return true;
		}
		if (o == null || getClass() != o.getClass())
		{
			return false;
		}

		final PosixNonClassPermissions that = (PosixNonClassPermissions) o;
		return setGroupIdentifierUponExecution == that.setGroupIdentifierUponExecution && setUserIdentifierUponExecution == that.setUserIdentifierUponExecution && stickyBit == that.stickyBit;
	}

	public int hashCode()
	{
		int result;
		result = (stickyBit ? 1 : 0);
		result = 31 * result + (setGroupIdentifierUponExecution ? 1 : 0);
		result = 31 * result + (setUserIdentifierUponExecution ? 1 : 0);
		return result;
	}
}
